﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Data;
using System.Linq;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.IO;

using System.Collections;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using Inference;


namespace Frames
{
    public partial class SlotForm : Form
    {
        public SlotForm(/*string _ConnectionString,*/ Modes _mode, Modes _frame_mode, int _FrameID, int _FrameType, int _SlotID, int _InsSlotNumber, bool _from_visual)
        {
            InitializeComponent();
            mode = _mode;
            frame_mode = _frame_mode;
            FrameID = _FrameID;
            SlotID = _SlotID;
            SlotNumber = _InsSlotNumber;
            from_visual = _from_visual;
            FrameType = _FrameType;
            Tale = new Inference.TaleEntities();
            //ConnectionString = _ConnectionString;
        }

        int SlotID, FrameID, Is_aID = -1, SlotDomID = -1, SlotDefValID = -1, SlotNumber = -1, ParentInhType = -1,
            DomID = -1, FrameType = -1, num_in_datat_frame = -1, dgProds_dragged_num = -1, SlotDomTypeForPicker = -1,
            ParentDomType = -1;
        bool from_visual, IfSubframe = false;
        Modes mode, frame_mode;
        string ConnectionString, FrameName = "", SlotName = "";
        SqlConnection conn; DataTable datat_frame;
        Inference.TaleEntities Tale; 

        private bool DomainIsSituation(int dom_id)
        {
            if (dom_id == 7)
                return true;
            return false;
        }

        private void LoadDomainNames()
        {
            //int dom_id = -1;
            //bool is_next = false;
            //cmb_domname.SelectedIndexChanged -= new System.EventHandler(cmb_domname_SelectedIndexChanged);
            //SqlCommand get_doms = new SqlCommand("", conn);
            //get_doms.CommandText = "select * from Domains";
            //if (mode == Modes.CREATE_SLOT)
            //    is_next = false;
            //else
            //    is_next = FrameType == 1 && datat_frame.Rows[num_in_datat_frame].ItemArray[1].ToString().ToLower() == "next";
            //SqlDataReader sread = get_doms.ExecuteReader();
            //while (sread.Read())
            //{
            //    dom_id = sread.GetInt32(0);
            //    if (is_next)
            //    {
            //        if (DomainIsSituation(dom_id))
            //            cmb_domname.Items.Add(sread.GetString(1));
            //    }
            //    else
            //        cmb_domname.Items.Add(sread.GetString(1));
            //}
            //sread.Close();
            //cmb_domname.SelectedIndexChanged += new System.EventHandler(cmb_domname_SelectedIndexChanged);
        }

        public int GetParentInheritType(string SlotName/*, int SlotNumber*/, int Is_aID)
        {
            int temp = -1;
            if (Is_aID >= 0)
            {
                SqlCommand get_inh_type = new SqlCommand("", conn);
                get_inh_type.CommandText = "select Inheritance from Slot where frameID=" + Is_aID.ToString()
                    + " and Name=\'" + SlotName + "\'"; // and Number=" + SlotNumber.ToString();
                SqlDataReader sread = get_inh_type.ExecuteReader();
                while (sread.Read())
                {
                    try
                    {
                        temp = sread.GetInt32(0);
                    }
                    catch
                    { temp = -1; }
                }
                sread.Close();
            }
            return temp;
        }

        private string GetDomainNameByID(int dom_id)
        {
            string temp = "";
            SqlCommand get_dom_name = new SqlCommand("", conn);
            get_dom_name.CommandText = "select Name from Domains where ID=" + dom_id.ToString();
            SqlDataReader sread = get_dom_name.ExecuteReader();
            while (sread.Read())
            {
                try
                {
                    temp = sread.GetString(0);
                }
                catch { }
            }
            sread.Close();
            return temp;
        }

        // not used if fixed depth in products
        public int GetParentSlotID(string SlotName/*, int SlotNumber*/, int Is_aID)
        {
            int temp = -1;
            if (Is_aID >= 0)
            {
                SqlCommand get_inh_type = new SqlCommand("", conn);
                get_inh_type.CommandText = "select ID from Slot where frameID=" + Is_aID.ToString()
                    + " and Name=\'" + SlotName + "\'"; // and Number=" + SlotNumber.ToString();
                SqlDataReader sread = get_inh_type.ExecuteReader();
                while (sread.Read())
                {
                    try
                    {
                        temp = sread.GetInt32(0);
                    }
                    catch
                    { temp = -1; }
                }
                sread.Close();
            }
            return temp;
        }

        private int GetIs_a(int frameID)
        {
            int is_a = -1;
            SqlCommand get_frame_name = new SqlCommand("", conn);
            get_frame_name.CommandText = "select Is_a from Frame where ID=" + frameID.ToString();
            SqlDataReader sread = get_frame_name.ExecuteReader();
            while (sread.Read())
            {
                try
                {
                    is_a = sread.GetInt32(0);
                }
                catch { is_a = -1; }
            }
            sread.Close();
            return is_a;
        }

        public string GetSlotSubFromFrame(int frame_id, int slot_id)
        {
            var slots = Tale.Slot.Where(v => v.FrameID == frame_id);
            var necess_subfr_ind = Tale.Slot.Where(v => v.ID == slot_id);

            if (necess_subfr_ind != null)
            {
                foreach (Inference.Slot sl in slots)
                {
                    if (sl.Domain == 1 || sl.Domain == 7)
                    {
                        var def_val = Tale.DValues.Where(v => v.ID == sl.DefaultValue);
                        if (def_val != null)
                        {
                            Inference.DValues df = def_val.First();
                            var subfr_ind = Tale.Frame.Where(v => v.Name.ToLower() == df.Value.ToLower());
                            if (subfr_ind != null)
                                if (subfr_ind.FirstOrDefault().ID == necess_subfr_ind.FirstOrDefault().FrameID)
                                {
                                    return subfr_ind.First().Name;
                                }
                        }
                    }
                }
            }
            else return "";
            return "";
        }

        public string CreateProdSlotName(int compSlotID, int place, string name, int prod_type)
        {
            Inference.Slot sl = null, sl1 = null;
            if (prod_type == 3)
            {
                var query = Tale.Slot.Where(v => v.ID == compSlotID);
                if (query != null)
                {
                    sl1 = query.First();
                    var subfr_ind = Tale.Frame.Where(v => v.ID == sl1.FrameID);
                    if (subfr_ind != null)
                    {
                        Inference.Frame sf_i = subfr_ind.First();
                        name = sf_i.Name + "." + sl1.Name;
                    }
                }
            }
            else
            {
                var place_query = Tale.Slot.Where(v => v.ID == place);
                if (place_query != null)
                {
                    sl = place_query.First();
                    name = sl.Name + name;
                }
                if (compSlotID != place)
                {
                    var query = Tale.Slot.Where(v => v.ID == compSlotID);
                    if (query != null)
                    {
                        sl1 = query.First();
                        name += "." + sl1.Name;
                    }
                    if (place_query != null && sl != null)
                    {
                        var def_val = Tale.DValues.Where(v => v.ID == sl.DefaultValue);
                        if (def_val != null)
                        {
                            Inference.DValues df = def_val.First();
                            var subfr_ind = Tale.Frame.Where(v => v.Name.ToLower() == df.Value.ToLower());
                            if (subfr_ind != null)
                            {
                                Inference.Frame sf_i = subfr_ind.First();
                                if (sf_i.ID != sl1.FrameID)
                                {
                                    string[] parts = name.Split('.');
                                    try
                                    {
                                        name = parts[0] + "." + GetSlotSubFromFrame(sf_i.ID, sl1.ID) + "." + parts[1];
                                    }
                                    catch { }
                                }
                            }
                        }
                    }
                }
            }
            return name;
            // if (frameID == -1)
            // {
            //     var comp_slot_name = Tale.Slot.Where(v => v.ID == compSlotID);                
            //     if (comp_slot_name != null)
            //     {
            //         sl = comp_slot_name.First();
            //         if (name != "")
            //             name = sl.Name + "." + name;
            //         else
            //             name = sl.Name;
            //     }
            // }
            // else
            // {
            //     var frame_name = Tale.Frame.Where(v => v.ID == frameID);                
            //     if (frame_name != null)
            //     {
            //         fr = frame_name.First();
            //         name = fr.Name + "." + name;
            //     }
            // }
            //// else
            // //    return name;

            // if (sl != null)
            // {
            //     if (compSlotID == place)
            //         return name;
            //     else
            //     {
            //         int is_a = GetIs_a(sl.FrameID);
            //         //if (is_a >= 0)
            //         //{
            //         //int new_ind = GetParentSlotID(sl.Name, is_a);
            //         return CreateProdSlotName(compSlotID, place, name, is_a);
            //         //}                
            //     }
            // }
            // else return name;
        }

        private void LoadProducts()
        {
            dgProds.Rows.Clear();
            // all rules premises
            //var prod_facts = (Tale.ViewProductions.Where(v => v.SlotID == SlotDomID).GroupBy(v => v.ProductionID)).OrderBy(v=>v.Type);
            var prod_facts = from p in Tale.ViewProductions where (p.SlotID == SlotID) orderby (p.Type) orderby (p.ProductionID) select p;//  group p by p.ProductionID;
            int i = -1, ins_i = -1, fact_in_prod_i = 0;
            bool if_fisrt_in_conc = true;
            foreach (Inference.ViewProductions pr_f in prod_facts)
            {
                if (i != pr_f.ProductionID)
                {
                    i = pr_f.ProductionID;
                    dgProds.Rows.Add();
                    ins_i++;
                    dgProds.Rows[ins_i].Cells[0].Value = pr_f.ProductionID;
                    fact_in_prod_i = 0;
                    if_fisrt_in_conc = true;
                }
                //else
                // {
                string str = "";
                var comp_value = Tale.DValues.Where(v => v.ID == pr_f.ValueID).First();
                //var comp_slot_name = Tale.Slot.Where(v => v.ID == pr_f.CompSlotID).First();
                string comp_slot_name = "";
                List<Slot> chain_slots = CheckIf.GetProductionChain((int)pr_f.Place, (int)pr_f.CompSlotID);//Tale.Slot.Where(v => v.ID == pr_f.CompSlotID).First();
                foreach (Slot sl in chain_slots)
                {
                    comp_slot_name += "'" + sl.Name + "'.";
                }
                if (comp_slot_name!="")
                    comp_slot_name = comp_slot_name.Substring(0, comp_slot_name.Length - 1);
                //string comp_slot_name = CreateProdSlotName((int)pr_f.CompSlotID, (int)pr_f.Place, comp_slot_name1, pr_f.Type);
                if (fact_in_prod_i > 0 && pr_f.Type == 1)
                    str = " И";
                str += " " + comp_slot_name/*.Name*/ +
                    (pr_f.Negation ? " != " : " = ") + comp_value.Value + " ";
                if (pr_f.Type == 1)
                {
                    dgProds.Rows[ins_i].Cells[1].Value += str;
                }
                else if (pr_f.Type == 2 || pr_f.Type == 3)
                {
                    dgProds.Rows[ins_i].Cells[2].Value += str;
                    if_fisrt_in_conc = false;
                }
                fact_in_prod_i++;
                //  }
            }
        }

        private void LoadSlotInformation()
        {
            bool error = false;
            //if (from_visual) // get from database
            {
                if (num_in_datat_frame >= 0)
                {
                    SqlDataReader sread;
                    int inh_type = -1; // свой тип наследования
                    SlotName = datat_frame.Rows[num_in_datat_frame].ItemArray[1].ToString();
                    txt_name.Text = datat_frame.Rows[num_in_datat_frame].ItemArray[1].ToString();
                    if (SlotName.Trim().ToLower() != "имя фрейма" && SlotName.Trim().ToLower() != "next")
                        IfSubframe = true;
                    else
                        IfSubframe = false;
                    txt_name.Select();
                    txt_name.Focus();

                    SlotNumber = (int)(datat_frame.Rows[num_in_datat_frame].ItemArray[7]);
                    ParentInhType = GetParentInheritType(txt_name.Text,/* SlotNumber,*/ Is_aID);
                    this.Text = "Редактирование слота " + txt_name.Text + " во фрейме " + FrameName;
                    if (txt_name.Text.ToLower() == "next" || txt_name.Text.ToLower() == "имя фрейма")
                    {
                        txt_name.Enabled = false;
                        cmb_inherit_type.Select();
                        cmb_inherit_type.Focus();
                        if (txt_name.Text.ToLower() == "next" && FrameName.Trim().ToLower() == "ситуация")
                            ucSlotPickerDomains.Enabled = false;
                    }

                    inh_type = (int)(datat_frame.Rows[num_in_datat_frame].ItemArray[8]) - 1;//sread.GetInt32(8) - 1;
                    if (inh_type >= 0)
                        cmb_inherit_type.SelectedIndex = inh_type;
                    DomID = (int)(datat_frame.Rows[num_in_datat_frame].ItemArray[2]);
                    string dom_name = GetDomainNameByID(DomID);
                    MakeDomainPicker(SlotID);
                    if (dom_name != "")
                    {
                        //cmb_domname.SelectedIndex = cmb_domname.Items.IndexOf(dom_name);
                        // LoadDomainValues();
                    }
                   
                    chb_alluwnull.Checked = (bool)(datat_frame.Rows[num_in_datat_frame].ItemArray[4]); //sread.GetBoolean(4);
                    txt_quest.Text = datat_frame.Rows[num_in_datat_frame].ItemArray[6].ToString(); //sread.GetString(6);                                       

                   // if (SlotDefValID >= 0)
                    {
                        SqlCommand get_def_val = new SqlCommand("", conn);
                        if (SlotDomTypeForPicker == 0)
                        {
                            SlotDefValID = (int)(datat_frame.Rows[num_in_datat_frame].ItemArray[3]);
                            get_def_val.CommandText = "select Value from DValues where ID=" + SlotDefValID.ToString();
                        }
                        else if (SlotDomTypeForPicker == 1)
                        {
                            SlotDefValID = (int)(datat_frame.Rows[num_in_datat_frame].ItemArray[3]);
                            get_def_val.CommandText = "select Name from Frame where ID=" + SlotDefValID.ToString();
                        }
                        sread = get_def_val.ExecuteReader();
                        string val = "";
                        if (sread.Read())
                        {
                            val = sread.GetString(0);
                            this.cmb_default_value.SelectedIndexChanged -= new System.EventHandler(this.cmb_default_value_SelectedIndexChanged);
                            cmb_default_value.SelectedIndex = cmb_default_value.Items.IndexOf(val);
                            this.cmb_default_value.SelectedIndexChanged += new System.EventHandler(this.cmb_default_value_SelectedIndexChanged);
                            if (cmb_default_value.SelectedIndex == -1)
                                error = true;
                        }
                        else
                            error = true;
                        sread.Close();
                        if (error)
                            MessageBox.Show("Ошибка при загрузке задания отсутствия!", "Ошибка");
                        else
                        {
                            //ParentInhType = GetParentInheritType(txt_name.Text, SlotNumber, Is_aID);
                            if (ParentInhType == 2) // == same
                            {
                                cmb_default_value.Enabled = false;
                                //cmb_domname.Enabled = false;
                                ucSlotPickerDomains.Enabled = false;
                            }
                        }
                    }
                    LoadProducts();
                }
            }
        }

        public void LoadSystemSlotsFromDB(SqlConnection conn, int FrameID)
        {
            SqlCommand get_frame_name = new SqlCommand("", conn);
            get_frame_name.CommandText = "select Name, Is_a from Frame where ID=" + FrameID.ToString();
            SqlDataReader sread = get_frame_name.ExecuteReader();
            while (sread.Read())
            {
                try
                {
                    FrameName = sread.GetString(0);
                }
                catch
                { FrameName = ""; }
                try
                {
                    Is_aID = sread.GetInt32(1);
                }
                catch { Is_aID = -1; }
            }
            sread.Close();
            #region is_a
            /*
            int temp_id = -1;
            SqlCommand get_frame_isa = new SqlCommand("", conn);
            get_frame_isa.CommandText = "select Is_a from Frame where ID=" + FrameID.ToString();
            SqlDataReader sread = get_frame_isa.ExecuteReader();
            while (sread.Read())
                if (sread.FieldCount == 1)
                    temp_id = sread.GetInt32(0);
                else temp_id = -1;
            sread.Close();
            return temp_id;*/
            #endregion
        }

        public DataTable LoadSlotsFromDB(SqlConnection conn, int FrameID)
        {
            DataTable dtFrameInformation;
            if (FrameID >= 0)
            {
                SqlCommand get_frame_slots = new SqlCommand("", conn);
                get_frame_slots.CommandText = "select * from Slot where FrameID=" + FrameID.ToString() +
                            " order by Number asc";
                SqlDataAdapter sadapt = new SqlDataAdapter(get_frame_slots);
                dtFrameInformation = new DataTable();
                sadapt.Fill(dtFrameInformation);
                // system slot                
            }
            else
            {
                MessageBox.Show("Не удалось получить информацию о фрейме!", "Ошибка");
                return null;
            }
            return dtFrameInformation;
        }

        private int GetLastSlotID()
        {
            int temp = -1;
            SqlCommand get_slot_id = new SqlCommand("", conn);
            get_slot_id.CommandText = "select max(ID) from Slot";
            SqlDataReader sread = get_slot_id.ExecuteReader();
            while (sread.Read())
                temp = sread.GetInt32(0);
            sread.Close();
            return temp;
        }

        private int CreateDefaultSlot()
        {
            int temp = -1;
            SqlCommand create_slot = new SqlCommand("", conn);
            create_slot.CommandText = "insert into Slot (Name,Domain,DefaultValue, AllowNull, " +
                "FrameID, Question,Number, Inheritance) values (\'Новый слот',1,NULL,0," +
                FrameID.ToString() + ", \'" +
                txt_quest.Text + "\', " +
                SlotNumber.ToString() + ", " +
                (cmb_inherit_type.SelectedIndex + 1).ToString() +
                ")";
            create_slot.ExecuteNonQuery();
            txt_name.Text = "Новый слот";
            SlotName = txt_name.Text;
            temp = GetLastSlotID();
            return temp;
        }

        private void MakeDomainPicker(int slotID)
        {
            if (slotID >= 0)
            {
                var slots = Tale.Slot.Where(v => v.ID == slotID);
                if (slots.Count() > 0 && slots.First().FrameID >= 0)
                {
                    // если создаем слот - грузим всё ParentSlotID=-1
                    // если редактируем слот, грузим домен родителя и выбираем домен
                    if (mode == Modes.CREATE_SLOT)
                    {
                        ucSlotPickerDomains.IfSubframe = IfSubframe;
                        ucSlotPickerDomains.InitDomainPicker();
                    }
                    else if (mode == Modes.EDIT_SLOT)
                    {
                        var slot = slots.First();
                        //if (slot.DomainType == null || slot.DomainType == 0)
                        //    SlotDomTypeForPicker = 0;
                        //else if (slot.DomainType != null && slot.DomainType > 0)
                        //    SlotDomTypeForPicker = 1;

                        // ucSlotPickerDomains.Picked -= new Inference.ucSlotPicker.PickedEventHandler(this.ucSlotPickerDomains_Picked);
                        if (CheckIf.SlotIsInherited(slot.Name, slot.Frame.Name))
                        {
                            var parent_slot = Tale.Slot.Where(v => v.Name == slot.Name && v.FrameID == slot.Frame.Is_a);
                            if (parent_slot.Count() > 0)
                            {
                                if (parent_slot.First().DomainType == null || parent_slot.First().DomainType == 0)
                                {
                                    ParentDomType = 0;
                                    ucSlotPickerDomains.InitDomainPicker(parent_slot.First().Domain, ParentDomType);
                                }
                                else if (parent_slot.First().DomainType != null && parent_slot.First().DomainType > 0)
                                {
                                    ParentDomType = 1;
                                    ucSlotPickerDomains.InitDomainPicker((int)parent_slot.First().DomainType, ParentDomType);
                                }
                                //ParentDomType = (int)parent_slot.First().DomainType; //Domain == 1 || parent_slot.First().Domain == 7) ? 1 : 0;

                            }
                        }
                        else
                        {
                            ucSlotPickerDomains.IfSubframe = IfSubframe;
                            ucSlotPickerDomains.InitDomainPicker();
                        }
                        ucSlotPickerDomains.InitFromSlot(slot);
                        //ucSlotPickerDomains.Picked += new Inference.ucSlotPicker.PickedEventHandler(this.ucSlotPickerDomains_Picked);
                        //// select domain
                        //if (slot.DomainType == null || slot.DomainType == 0)
                        //    SlotDomTypeForPicker = 0;
                        //else if (slot.DomainType != null && slot.DomainType > 0)
                        //    SlotDomTypeForPicker = 1;
                        ////SlotDomTypeForPicker = (int)slot.DomainType;

                        //// ucSlotPickerDomains.SelectedDomainType = SlotDomTypeForPicker;
                        //if (SlotDomTypeForPicker == 1)
                        //{
                        //    ucSlotPickerDomains.SelectedDomainID = (int)slot.DomainType;
                        //}
                        //else if (SlotDomTypeForPicker == 0)
                        //{
                        //    ucSlotPickerDomains.SelectedDomainID = (int)slot.Domain;
                        //}
                        ////ucSlotPickerDomains.Picked -= new Inference.ucSlotPicker.PickedEventHandler(this.ucSlotPickerDomains_Picked);
                        ////(slot.Domain == 1 || slot.Domain == 7) ? 1 : 0;
                        //// ucSlotPickerDomains.InitDomainPicker(slot.Domain, SlotDomTypeForPicker);
                        ////ucSlotPickerDomains.Picked += new Inference.ucSlotPicker.PickedEventHandler(this.ucSlotPickerDomains_Picked);
                    }
                }
            }
        }

        // FORM
        private void Slot_Load(object sender, EventArgs e)
        {
            ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + Directory.GetCurrentDirectory() +
                "\\Tale.mdf" + ";Integrated Security=True;Connect Timeout=30;User Instance=True";
            conn = new SqlConnection(ConnectionString);
            conn.Open();
            cmb_inherit_type.SelectedIndex = 0;
            // !!!!
            if (from_visual && mode == Modes.EDIT_SLOT) // || frame_mode == Modes.CREATE_FRAME)
            {
                var slot = from p in Tale.Slot where (p.ID == SlotID) select p;
                if (slot != null)
                    foreach (Inference.Slot sl in slot)
                        FrameID = sl.FrameID;
            }
            LoadSystemSlotsFromDB(conn, FrameID);
            datat_frame = LoadSlotsFromDB(conn, FrameID);

            //else
            //{
            // get from structure
            //}
            if (datat_frame != null && datat_frame.Rows.Count >= 0) // >= !!!
            {
                for (int i = 0; i < datat_frame.Rows.Count; i++)
                    if (datat_frame.Rows[i].ItemArray[0].ToString() == SlotID.ToString())
                    {
                        num_in_datat_frame = i;
                    }

                //LoadDomainNames();
                if (mode == Modes.EDIT_SLOT)
                {
                    LoadSlotInformation();
                }
                else if (mode == Modes.CREATE_SLOT)
                {
                    this.Text = "Создание слота во фрейме: " + FrameName;
                    if (from_visual)
                    {
                        if (datat_frame.Rows.Count == 0)
                            SlotNumber = 0;
                        else if (FrameType == 1)
                            SlotNumber = datat_frame.Rows.Count - 2;
                        else if (FrameType == 2)
                            SlotNumber = datat_frame.Rows.Count - 1;
                    }
                    if (SlotNumber < 0) // "если косяк", по идее.
                        SlotNumber = 0;
                    SlotID = CreateDefaultSlot();
                    if (SlotName.Trim().ToLower() != "имя фрейма" && SlotName.Trim().ToLower() != "next")
                        IfSubframe = true;
                    else
                        IfSubframe = false;
                    MakeDomainPicker(SlotID);
                    //cmb_domname.SelectedIndex = 0;
                }                       
            }
            else // не смогли загрузить информацию
            {
                MessageBox.Show("Не удалось загрузить информацию о фрейме слота!", "Ошибка");
                this.Text = "Редактирование слота";
                splitContainer1.Enabled = false;
                btn_OK.Enabled = false;
            }
        }


        private void SlotForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            conn.Close();
        }

        private void cmb_domname_Validated(object sender, EventArgs e)
        {
            //bool is_in_cmbvar = false;
            //string curr_value = cmb_domname.Text;
            //for (int i = 0; i < cmb_domname.Items.Count; i++)
            //    if (curr_value.ToLower().Trim() == cmb_domname.Items[i].ToString().ToLower().Trim())
            //    {
            //        is_in_cmbvar = true;
            //        cmb_domname.SelectedIndex = i; // cmb_domname.Items[i];
            //        break;
            //    }
            //if (!is_in_cmbvar)
            //{
            //    // ContexFill DomainsForm domf = new DomainsForm(); domf.ShowDialog();
            //}
        }

        private void LoadDomainValues()
        {
            dgDomVals.Rows.Clear();
            cmb_default_value.Items.Clear();
            if (SlotDomID >= 0)
            {
                if (SlotDomTypeForPicker == 0)
                {
                    var dvals = Tale.DomainsValues.Where(v => v.DomID == SlotDomID).OrderBy(v => v.Number);
                    foreach (Inference.DomainsValues dv in dvals)
                    {
                        var value = Tale.DValues.Where(v => v.ID == dv.Value).First();
                        dgDomVals.Rows.Add(value.Value);
                        cmb_default_value.Items.Add(value.Value);
                    }
                    if (cmb_default_value.Items.Count > 0)
                    {
                        this.cmb_default_value.SelectedIndexChanged -= new System.EventHandler(this.cmb_default_value_SelectedIndexChanged);
                        cmb_default_value.SelectedIndex = 0;
                        this.cmb_default_value.SelectedIndexChanged += new System.EventHandler(this.cmb_default_value_SelectedIndexChanged);
                    }
                }
                else if (SlotDomTypeForPicker == 1) // фрейм
                {
                    List<Frame> frame_values = CheckIf.GetFrameDomain(ucSlotPickerDomains.SelectedDomainID, Tale);
                    foreach (Frame fr in frame_values)
                    {
                        dgDomVals.Rows.Add(fr.Name);
                        cmb_default_value.Items.Add(fr.Name);
                    }
                    if (cmb_default_value.Items.Count > 0)
                    {
                        this.cmb_default_value.SelectedIndexChanged -= new System.EventHandler(this.cmb_default_value_SelectedIndexChanged);
                        cmb_default_value.SelectedIndex = 0;
                        this.cmb_default_value.SelectedIndexChanged += new System.EventHandler(this.cmb_default_value_SelectedIndexChanged);
                    }
                }
            }
        }

        private void cmb_domname_SelectedIndexChanged(object sender, EventArgs e)
        {
            // SlotDomID = GetDomainIDByName(cmb_domname.Text);
            // LoadDomainValues();
        }

        private void cmb_default_value_Validated(object sender, EventArgs e)
        {
            bool is_in_cmbvar = false;
            string curr_value = cmb_default_value.Text;
            for (int i = 0; i < cmb_default_value.Items.Count; i++)
                if (curr_value.ToLower().Trim() == cmb_default_value.Items[i].ToString().ToLower().Trim())
                {
                    is_in_cmbvar = true;
                    cmb_default_value.SelectedIndex = i; // cmb_domname.Items[i];
                    break;
                }
            if (!is_in_cmbvar)
            {
                // ContexFill Добавление значения в домен.
            }
        }

        private int GetDomainIDByName(string dom_name)
        {
            int temp = -1;
            SqlCommand get_dom_id = new SqlCommand("", conn);
            get_dom_id.CommandText = "select ID from Domains where Name=\'" + dom_name + "\'";
            SqlDataReader sread = get_dom_id.ExecuteReader();
            while (sread.Read())
            {
                try
                {
                    temp = sread.GetInt32(0);
                }
                catch { }
            }
            sread.Close();
            return temp;
        }

        private int GetDefValID(int dom_id)
        {
            if (SlotDomTypeForPicker == 0)
            {
                var dom_val_ids = from p in Tale.DomainsValues where (p.DomID == dom_id) orderby (p.Number) select p;
                foreach (Inference.DomainsValues dv in dom_val_ids)
                {
                    if (Tale.DValues.Where(v => v.ID == dv.Value && v.Value == cmb_default_value.Text).Count() > 0)
                        return dv.Value;
                }
                return -1;
            }
            else if (SlotDomTypeForPicker == 1) // фрейм
            {
                List<Frame> frame_values = CheckIf.GetFrameDomain(ucSlotPickerDomains.SelectedDomainID, Tale);
                foreach (Frame fr in frame_values)
                {
                    if (cmb_default_value.Text.Trim().ToLower() == fr.Name.Trim().ToLower())
                        return fr.ID;
                    //dgDomVals.Rows.Add(fr.Name);
                    //cmb_default_value.Items.Add(fr.Name);
                }
                return -1;
            }
            return -1;
        }

        private void UpdateDown(int frameID, bool same_inh_chain, int def_value_id, int dom_id, int dom_type)
        {
            if (frameID >= 0)
            {
                var child_frames = from p in Tale.Frame where (p.Is_a == frameID) select p;
                foreach (Inference.Frame fr in child_frames)
                {
                    SqlCommand get_frame_slots = new SqlCommand("", conn);
                    get_frame_slots.CommandText = "select * from Slot where FrameID=" + fr.ID.ToString() +
                                " order by Number asc";
                    SqlDataAdapter sadapt = new SqlDataAdapter(get_frame_slots);
                    DataTable dtframe = new DataTable();
                    sadapt.Fill(dtframe);
                    string query = "";
                    if (!same_inh_chain)
                        query = "update Slot set Name=\'" + txt_name.Text +
                                "' where ID=" + dtframe.Rows[num_in_datat_frame].ItemArray[0].ToString();
                    else
                        query = "update Slot set Name=\'" + txt_name.Text +
                                "',Domain=" + dom_id.ToString() +
                                ",DomainType=" + dom_type.ToString() +
                                ", DefaultValue=" + def_value_id.ToString() +
                                " where ID=" + dtframe.Rows[num_in_datat_frame].ItemArray[0].ToString();
                    SqlCommand update_slot = new SqlCommand("", conn);
                    update_slot.CommandText = query;
                    update_slot.ExecuteNonQuery();
                    if ((int)dtframe.Rows[num_in_datat_frame].ItemArray[8] != 2)
                        same_inh_chain = false;
                    UpdateDown(fr.ID, same_inh_chain, def_value_id, dom_id, dom_type);
                }
            }
        }

        private void CreateDown(int slotID)
        {
            var children = CheckIf.ChildrenOf(FrameName, true, Tale);
            var slot = Tale.Slot.Where(v => v.ID == slotID).First();
            SqlCommand create_slot = new SqlCommand("", conn);
            foreach (Inference.Frame fr in children)
            {
                // insert
                try
                {
                    Slot new_slot = new Slot();
                    new_slot.Name = slot.Name;
                    new_slot.Number = slot.Number;
                    new_slot.AllowNull = slot.AllowNull;
                    new_slot.Inheritance = slot.Inheritance;
                    new_slot.DefaultValue = slot.DefaultValue;
                    new_slot.Domain = slot.Domain;
                    new_slot.DomainType = slot.DomainType;
                    new_slot.FrameID = fr.ID;
                    new_slot.Question = txt_name.Text + " - ?"; 
                    Tale.Slot.AddObject(new_slot);
                    Tale.SaveChanges();
                    ReindexSlotsAdd(new_slot.ID, fr.ID);
                }
                catch
                {
                    MessageBox.Show("Ошибка при создании слота!", "Ошибка");
                }
                //int ind = GetLastSlotID();
                //if (ind!=-1)
                //{
                //    var new_slots = Tale.Slot.Where(v => v.ID == ind);
                //    try
                //    {
                //        var new_slot = new_slots.First();
                //        new_slot.FrameID = fr.ID;
                //        new_slot.Question = "Каково значение слота " + slot.Name +
                //                                " из фрейма " + fr.Name + "?";
                //        Tale.SaveChanges();
                //    }
                //    catch { }
                //}                
            }
        }

        string GetRoot(int FrameID)
        {
            Frame fr;
            do
            {
                fr = Tale.Frame.Where(f => f.ID == FrameID).First();
                if (fr.Is_a.HasValue)
                    FrameID = fr.Is_a.Value;
                else
                    FrameID = 0;
            }
            while (FrameID != 0);
            return fr.Name;
        }

        private void UpdateSlotInDB(int slotID)
        {
            int dom_id = ucSlotPickerDomains.SelectedDomainID; //GetDomainIDByName(cmb_domname.Text);
            //if (cmb_default_value.SelectedIndex == -1)
            //    def_value = "NULL";
            //else
            int def_value_id = GetDefValID(dom_id);
            int dom_type = -1;
            bool cancel = false;
            try
            {
                Slot slot = Tale.Slot.Where(v => v.ID == slotID).First();
                SqlCommand update_slot = new SqlCommand("", conn);
                if (SlotDomTypeForPicker == 0) // common & system
                {
                    dom_type = 0;
                    slot.Name = txt_name.Text;
                    slot.Domain = dom_id;
                    slot.DefaultValue = def_value_id;
                    slot.AllowNull = chb_alluwnull.Checked;//((chb_alluwnull.Checked) ? 1 : 0);
                    slot.Question = txt_quest.Text;
                    slot.Inheritance = cmb_inherit_type.SelectedIndex + 1;
                    slot.DomainType = dom_type;
                    slot.Number = SlotNumber;

                    //update_slot.CommandText =
                    //    "update Slot set Name=\'" + txt_name.Text + "\'," +
                    //    " Domain=" + dom_id.ToString() + ", DefaultValue=" + def_value_id.ToString() + ", " +
                    //    " AllowNull=" + ((chb_alluwnull.Checked) ? "1" : "0") + ", " +
                    //    " Question=\'" + txt_quest.Text.ToString() + "\', " +
                    //    " Inheritance=" + (cmb_inherit_type.SelectedIndex + 1).ToString() + ", " +
                    //    " DomainType=" + dom_type.ToString()/* + (ucSlotPickerDomains.SelectedDomainType).ToString()*/ + ", " +
                    //    " Number=" + SlotNumber.ToString() +
                    //    " where ID=" + slotID.ToString();
                }
                else
                {
                    //int domain_id =0;
                    if (GetRoot(FrameID).Trim().ToLower() == "ситуация")
                        dom_id = 7;
                    else
                        dom_id = 1;
                    dom_type = ucSlotPickerDomains.SelectedDomainID;

                    slot.Name = txt_name.Text;
                    slot.Domain = dom_id;
                    slot.DefaultValue = def_value_id;
                    slot.AllowNull = chb_alluwnull.Checked;//((chb_alluwnull.Checked) ? 1 : 0);
                    slot.Question = txt_quest.Text;
                    slot.Inheritance = cmb_inherit_type.SelectedIndex + 1;
                    slot.DomainType = dom_type;
                    slot.Number = SlotNumber;

                    //update_slot.CommandText =
                    //   "update Slot set Name=\'" + txt_name.Text + "\'," +
                    //   " Domain=" + dom_id.ToString() + ", DefaultValue=" + def_value_id.ToString() + ", " +
                    //   " AllowNull=" + ((chb_alluwnull.Checked) ? "1" : "0") + ", " +
                    //   " Question=\'" + txt_quest.Text.ToString() + "\', " +
                    //   " Inheritance=" + (cmb_inherit_type.SelectedIndex + 1).ToString() + ", " +
                    //   " DomainType=" + (dom_type).ToString() + ", " +
                    //   " Number=" + SlotNumber.ToString() +
                    //   " where ID=" + slotID.ToString();
                }
                Tale.SaveChanges();
                //update_slot.ExecuteNonQuery();
            }
            catch
            {
                MessageBox.Show("Ошибка при создании слота!", "Ошибка");
                cancel = true;
            }
            if (!cancel)
            {
                if (mode == Modes.EDIT_SLOT)
                {
                    // update down hier. тупо апдейт - проверки во Фрейме
                    if (cmb_inherit_type.SelectedIndex + 1 == 1)
                        UpdateDown(FrameID, false, def_value_id, dom_id, dom_type);
                    else if (cmb_inherit_type.SelectedIndex + 1 == 2)
                        UpdateDown(FrameID, true, def_value_id, dom_id, dom_type);
                }
                else if (mode == Modes.CREATE_SLOT)
                {
                    // create down hier.                
                    CreateDown(slotID);
                }
            }
        }

        private void ReindexSlotsAdd(int slotID, int frameID)   // numbers
        {
            bool first = true; int ind = 0;
            DataTable datat_fr = LoadSlotsFromDB(conn, frameID);
            for (int i = 0; i < datat_fr.Rows.Count; i++)
            {
                if ((int)datat_fr.Rows[i].ItemArray[0] != slotID
                    && (int)datat_fr.Rows[i].ItemArray[7] >= SlotNumber)
                {
                    if (first)
                    {
                        ind = SlotNumber + 1;
                        first = false;
                    }
                    try
                    {
                        SqlCommand update_slot = new SqlCommand("", conn);
                        update_slot.CommandText =
                            "update Slot set Number=" + (ind).ToString() +
                            " where ID=" + ((int)datat_fr.Rows[i].ItemArray[0]).ToString();
                        update_slot.ExecuteNonQuery();
                    }
                    catch { }
                    ind++;
                }
            }
        }

        private void CreateSlotInDB()
        {
            SqlCommand create_slot = new SqlCommand("", conn);
            int dom_id = ucSlotPickerDomains.SelectedDomainID;//GetDomainIDByName(cmb_domname.Text);
            create_slot.CommandText = "insert into Slot (Name,Domain,DefaultValue, AllowNull, " +
                "FrameID, Question,Number, Inheritance) values (\'" +
                txt_name.Text + "\'," + dom_id.ToString() + ", " +
                 GetDefValID(dom_id).ToString() + ", " +
                ((chb_alluwnull.Checked) ? "1" : "0") + ", " +
                FrameID.ToString() + ", \'" +
                txt_quest.Text + "\', " +
                SlotNumber.ToString() + ", " +
                (cmb_inherit_type.SelectedIndex + 1).ToString() +
                ")";
            create_slot.ExecuteNonQuery();
        }

        private bool SlotNameIsUnique(int SlotID, string slot_name, string frameName, bool recursive)
        {
            List<Slot> res = new List<Slot>();
            
            if (mode == Modes.EDIT_SLOT)
            {
                var ss = Tale.Slot.Where(s => s.Name.ToLower().Trim() == slot_name.ToLower().Trim() && s.Number != SlotNumber && s.Frame.Name == frameName);
                if (ss.Count() > 0)
                    return false;
            }
            else if (mode == Modes.CREATE_SLOT)
            {
                var ss = Tale.Slot.Where(s => (s.Name.ToLower().Trim() == slot_name.ToLower().Trim() && (s.Frame.Name == frameName 
                    && frameName != FrameName || frameName == FrameName && s.Number != SlotNumber)));
                if (ss.Count() > 0)
                    return false;
            }
            
            if (recursive)
            {
                var children = from fCurrent in Tale.Frame
                               join fAnother in Tale.Frame on fCurrent.ID equals fAnother.Is_a
                               where fCurrent.Name == frameName
                               select fAnother;
                foreach (Frame f in children)
                {
                    if (!SlotNameIsUnique(SlotID, slot_name, f.Name, true))
                        return false;
                }
            }
            return true;
        }

        private bool CalledNext(Slot slot)
        {
            if (slot.Name.Trim().ToLower() == txt_name.Text.Trim().ToLower()
                && txt_name.Text.Trim().ToLower() == "next")
                return false;
            else if (slot.Name.Trim().ToLower() != txt_name.Text.Trim().ToLower()
                && txt_name.Text.Trim().ToLower() == "next")
                return true;
            return false;
        }

        private bool CalledFrameName(Slot slot)
        {
            if (slot.Name.Trim().ToLower() == txt_name.Text.Trim().ToLower()
                && txt_name.Text.Trim().ToLower() == "имя фрейма")
                return false;
            else if (slot.Name.Trim().ToLower() != txt_name.Text.Trim().ToLower()
                && txt_name.Text.Trim().ToLower() == "имя фрейма")
                return true;
            return false;
        }

        private bool SubAndCanCreate(Slot slot)
        {
            if (txt_name.Text.Trim().ToLower() != "next" && SlotDomTypeForPicker == 1 &&
                (cmb_default_value.Text.Trim().ToLower() == "ситуация" || !CheckIf.LinkSUBCouldBeCreated(cmb_default_value.Text, slot.Frame.Name)))
            {
                return false;
            }
            return true;
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            //if (from_visual)
            //{
            bool cancel = false;
            Slot slot = null;
            try
            {
                slot = Tale.Slot.Where(v => v.ID == SlotID).First();
            }
            catch { cancel = true; }
            if (!cancel)
            {
                if (txt_name.Text.Trim() != "")
                {
                    if (cmb_default_value.Text.Trim() != "")    // ???
                    {
                        if (!CalledNext(slot))
                        {
                            if (!CalledFrameName(slot))
                            {
                                if (SubAndCanCreate(slot))
                                {
                                    if (SlotNameIsUnique(SlotID, txt_name.Text, FrameName, true))
                                    {
                                        if (ucSlotPickerDomains.SelectedDomainID >= 0)//cmb_domname.Text.Trim() != "")
                                        {
                                            int dom_id = ucSlotPickerDomains.SelectedDomainID;//GetDomainIDByName(cmb_domname.Text);
                                            if (dom_id >= 0)
                                            {
                                                if (GetDefValID(dom_id) >= 0)
                                                {
                                                    if (txt_quest.Text == "")
                                                        txt_quest.Text = txt_name.Text + " - ?";
                                                    //if (mode == Modes.CREATE_SLOT)
                                                    //{
                                                    //    CreateSlotInDB();
                                                    //    this.DialogResult = DialogResult.OK;
                                                    //    this.Close();
                                                    //}
                                                    //else if (mode == Modes.EDIT_SLOT)
                                                    //{
                                                    UpdateSlotInDB(SlotID);
                                                    if (mode == Modes.CREATE_SLOT)
                                                        ReindexSlotsAdd(SlotID, FrameID);
                                                    this.DialogResult = DialogResult.OK;
                                                    this.Close();
                                                    //}
                                                }
                                                else
                                                {
                                                    MessageBox.Show("Выбранное задание отсутствия не существует в базе данных!", "Ошибка");
                                                    cmb_default_value.Focus();
                                                }

                                            }
                                            else
                                            {
                                                MessageBox.Show("Выбранный домен значений слота не существует в базе данных!", "Ошибка");
                                                ucSlotPickerDomains.Focus();
                                            }
                                        }
                                        else
                                        {
                                            MessageBox.Show("Не выбран домен значений слота!", "Ошибка");
                                            ucSlotPickerDomains.Focus();
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("Слот с таким именем уже существует во фрейме!", "Ошибка");
                                        txt_name.Focus();
                                    }
                                }
                            }
                            else
                            {
                                MessageBox.Show("Имя слота 'Имя фрейма' является системным!", "Ошибка");
                                txt_name.Focus();
                            }
                        }
                        else
                        {
                            MessageBox.Show("Имя слота 'Next' является системным!", "Ошибка");
                            txt_name.Focus();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Не выбрано задание отсутствие слота!", "Ошибка");
                        cmb_default_value.Focus();
                    }
                }
                else
                {
                    MessageBox.Show("Не задано имя слота!", "Ошибка");
                    txt_name.Focus();
                }
            }
            // }
            // else
            //{
            // create structure???
            //}
        }

        private void cmb_default_value_SelectedIndexChanged(object sender, EventArgs e)
        {
            int dom_id = ucSlotPickerDomains.SelectedDomainID;//GetDomainIDByName(cmb_domname.Text);
            int def_val_id = GetDefValID(dom_id);
            if (dom_id >= 0)
            {
                //var dom_val_ids = from p in Tale.DomainsValues where (p.DomID == dom_id) orderby (p.Number) select p;
                //foreach (Inference.DomainsValues dv in dom_val_ids)
                if (SlotID >= 0 && def_val_id >= 0)
                {
                    //var def_val_id = Tale.DValues.Where(v => v.ID == dv.Value).First();
                    Inference.LV lv = new Inference.LV(ConnectionString);
                    if (!lv.CheckSlotValue1(SlotID, def_val_id/*.ID*/))
                    {
                        MessageBox.Show("Выбранное задание отсутствия не удовлетворяет маркерам слота!", "Ошибка");
                        cmb_default_value.Focus();
                    }
                }
            }
        }


        private void cmb_inherit_type_SelectedIndexChanged(object sender, EventArgs e)
        {
            // CheckMarkers();
        }

        private int DeleteProduction(int slotID, int prodID)
        {
            if (slotID >= 0)
            {
                SqlCommand get_facts, delete_prod;
                DataTable df = new DataTable();
                try
                {
                    get_facts = new SqlCommand("", conn);
                    get_facts.CommandText = "select * from Fact where SlotID=" + slotID;
                    SqlDataAdapter sadapt = new SqlDataAdapter(get_facts);
                    sadapt.Fill(df);
                }
                catch
                { return -1; }
                for (int i = 0; i < df.Rows.Count; i++)
                //foreach (Inference.Fact sf in slot_facts)
                {
                    try
                    {
                        delete_prod = new SqlCommand("", conn);
                        delete_prod.CommandText = "delete from ProductionFact where FactID=" + df.Rows[i].ItemArray[0]; //sf.ID;
                        if (prodID != -1)
                            delete_prod.CommandText += " and ProductionID=" + prodID.ToString();
                        delete_prod.ExecuteNonQuery();
                    }
                    catch { return -1; }
                }
                for (int i = 0; i < df.Rows.Count; i++)
                //foreach (Inference.Fact sf in slot_facts)
                {
                    try
                    {
                        delete_prod = new SqlCommand("", conn);
                        delete_prod.CommandText = "delete from Fact where ID=" + df.Rows[i].ItemArray[0]; //sf.ID;
                        delete_prod.ExecuteNonQuery();
                    }
                    catch { return -1; }
                }
                return 0;
            }
            else return -1;
        }

        public int DeleteSlotFromVisual(int slotID, int frameType)
        {
            // ПРОВЕРКИ
            var slot = Tale.Slot.Where(v => v.ID == slotID);
            try
            {
                int frame_id = slot.First().FrameID;
                SlotFrameFuncs.DeleteSlot(slotID, Tale);
                SlotFrameFuncs.ReindexSlots(frame_id);//, Tale);

                return 0;
            }
            catch
            {
                MessageBox.Show("Ошибка при удалении слота!", "Ошибка", MessageBoxButtons.OK);
                return -1;
            }
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            if (mode == Modes.CREATE_SLOT)
            {
                SlotFrameFuncs.DeleteSlot(SlotID, Tale);
                this.Close();
            }
            else if (mode == Modes.EDIT_SLOT)
            {
                this.Close();
            }
        }

        private void dgProds_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dgProds_dragged_num != -1 && e.RowIndex != -1 && dgProds.Columns.Count > 0
                && e.RowIndex != dgProds.Rows.Count && dgProds_dragged_num != e.RowIndex)
            {
                object[] vals = new object[dgProds.Columns.Count];
                for (int i = 0; i < dgProds.Columns.Count; i++)
                    vals[i] = dgProds.Rows[dgProds_dragged_num].Cells[i].Value;
                for (int i = 0; i < dgProds.Columns.Count; i++)
                    dgProds.Rows[dgProds_dragged_num].Cells[i].Value = dgProds.Rows[e.RowIndex].Cells[i].Value;
                for (int i = 0; i < dgProds.Columns.Count; i++)
                    dgProds.Rows[e.RowIndex].Cells[i].Value = vals[i];
            }
        }

        private void dgProds_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex != -1 && e.RowIndex < dgProds.Rows.Count)
                dgProds_dragged_num = e.RowIndex;
        }

        private void dgProds_SelectionChanged(object sender, EventArgs e)
        {
            if (dgProds.SelectedCells != null && dgProds.SelectedCells.Count > 0)
            {
                // btn_del_prod.Enabled = true;
            }
        }

        private void btn_del_prod_Click(object sender, EventArgs e)
        {
            if (dgProds.SelectedCells != null && dgProds.SelectedCells.Count > 0)
            {
                if (MessageBox.Show("Вы действительно хотите удалить продукцию?", "Внимание", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    if (DeleteProduction(SlotID, (int)dgProds.SelectedCells[0].Value) == 0)
                        dgProds.Rows.RemoveAt(dgProds.SelectedCells[0].RowIndex);
                }
            }
        }

        private void btn_upd_prod_Click(object sender, EventArgs e)
        {
            if (dgProds.SelectedCells != null && dgProds.SelectedCells.Count > 0)
            {
                Inference.frmProduct fpr = new Inference.frmProduct(true, (int)dgProds.SelectedCells[0].Value, SlotID, FrameID);
                DialogResult dr = fpr.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    dgProds.Rows.Clear();
                    LoadProducts();
                }
            }
        }

        private void btn_add_prod_Click(object sender, EventArgs e)
        {
            if (dgProds.SelectedCells != null && dgProds.SelectedCells.Count > 0 || dgProds.Rows.Count == 0)
            {
                Inference.frmProduct fpr = new Inference.frmProduct(false, -1, SlotID, FrameID);
                DialogResult dr = fpr.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    dgProds.Rows.Clear();
                    LoadProducts();
                }
            }
        }

        private void ucSlotPickerDomains_Picked()
        {
            SlotDomID = ucSlotPickerDomains.SelectedDomainID;
            SlotDomTypeForPicker = ucSlotPickerDomains.SelectedDomainType;
            //if (SlotName.Trim().ToLower()=="next")
             //   SlotDomTypeForPicker = 0;
            LoadDomainValues();   //  там через SlotDomID
        }
    }
}
